package com.xinzhi.savingpot.background.controller;

import com.xinzhi.savingpot.util.MD5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

//处理http请求，标明这个类为controller层的类，并且注入到spring容器中
@Controller
public class UserController {
    /**
     * 增
     * 将特定的URL映射到指定的方法
     */
    @GetMapping("/user/add")
    public String add() {
        return "add";
    }

    /**
     * 改
     */
    @GetMapping("/user/update")
    public String update() {
        return "update";
    }
    /**
     * 删除
     */
    @GetMapping("/dele")
    public String dele(){
        return "dele";
    }

    /**
     * 跳转到登录页面
     */
    @GetMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public String login(@RequestParam(value = "userName") String userName,  //RequestParam（value =）里面穿的参数为什么，前端就传什么
                        @RequestParam(value = "password") String password,
                        Model model) {
        //获取当前对象
        Subject subject = SecurityUtils.getSubject();
        //封装数据库的登录数据，生成令牌加密
        UsernamePasswordToken token = new UsernamePasswordToken(userName, MD5Util.stringMD5(password));
        try {
            //执行登录方法，如果没有异常就说明登录成功了
            subject.login(token);
            return "index";
        } catch (AuthenticationException e){
            model.addAttribute("msg","错误");
            return "login";
        }
    }

    @GetMapping("/unauth")
    public String unauthoried() {
        return "unauth";
    }
}